import { types, visit } from "recast";

const { expressionStatement, assignmentExpression } = types.builders;

/**
 * 分解声明时的初始化语句
 */
const modifyDeclarationInit = (ast) => {
  visit(ast, {
    visitVariableDeclaration: function (path) {
      // 只处理正常的声明语句，对类似for循环中的声明语句不做处理
      if (path.name != "init" && path.name != "left") {
        // let 防止 const 无法赋值
        path.node.kind = "let";
        const newStatement = path.node.declarations
          .filter((l) => l.init != null)
          .map((declaration) => {
            const exp = expressionStatement(
              assignmentExpression("=", declaration.id, declaration.init)
            );
            declaration.init = null;
            return exp;
          });
        const parentPath = path.insertAfter(...newStatement);
        // 这种情况是为了处理新的assignmentExpression赋值语句中，可能存在的初始化语句
        // 例子：var f = (function () { const result = d === 1 ? (d = 1) : (d = 2); return 1})();
        parentPath.each((childPath) => {
          if (newStatement.includes(childPath.node)) {
            this.visit(childPath);
          }
        });
      }
      return false;
    },
  });
};

export default modifyDeclarationInit;
